package devserv

import (
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"log"
	"message"
	"rhelper"
	"time"
)

var (
	leftOnWait = make(map[string]chan bool)
)

func setLeftOnNotifyIfRelayOpen(msgBuf []byte, cid string) {
	type RelayRequest struct {
		Uri    string `json:"uri"`
		Action string `json:"action"`
	}

	relayRequst := RelayRequest{}
	err := json.Unmarshal(msgBuf, &relayRequst)
	if err != nil {
		log.Println("onUserRequest failed, json decode failed:", err)
		return
	}

	if relayRequst.Uri != "/relay" {
		return
	}

	discardLeftOnWait(cid)

	if relayRequst.Action != "open" {
		return
	}

	go waitLeftOnNotify(cid)

}

func waitLeftOnNotify(cid string) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	values, err := redis.Ints(rconn.Do("HMGET", rhelper.ControllerHash+cid, "leftOnEnable", "leftOnTime"))
	if err != nil {
		log.Println("get controller account err: ", err)
		return
	}

	enable := values[0]
	leftOnTime := values[1]

	if enable != 1 {
		return
	}

	if leftOnTime <= 0 {
		return
	}

	log.Println("waitLeftOnNotify")
	discardLeftOnWait := make(chan bool, 1)
	leftOnWait[cid] = discardLeftOnWait
	select {
	case <-discardLeftOnWait:
		return
	case <-time.After(time.Minute * time.Duration(leftOnTime)):
		delete(leftOnWait, cid)
		sendLeftOnNotify(cid, leftOnTime)
		break
	}
}

func discardLeftOnWait(cid string) {
	log.Println("discardLeftOnWait")
	wait, ok := leftOnWait[cid]
	if !ok {
		return
	}

	wait <- true
	close(wait)
	delete(leftOnWait, cid)
}

func sendLeftOnNotify(cid string, waitTime int) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	values, err := redis.Strings(rconn.Do("HMGET", rhelper.ControllerHash+cid, "account", "leftOnEnable"))
	if err != nil {
		log.Println("get controller err: ", err)
		return
	}

	account := values[0]
	leftOnEnable := values[1]
	if leftOnEnable != "1" {
		log.Println("LeftOn notify was disable")
		return
	}

	h := waitTime / 60
	m := waitTime % 60
	waitTimeStr := fmt.Sprintf("%d hour %d minute", h, m)

	msg := message.Message{}
	msg.Type = "leftOn"
	msg.To = account
	msg.From = cid
	msg.FromName = getControllerAlias(cid)
	msg.Title = "Left on message"
	msg.Abstract = "OutLet " + msg.FromName + " has been open " + waitTimeStr

	message.SendMessage(msg, cid)
}
